package com.interview.communication;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 【方式3】BlockingQueue 阻塞队列
 * 线程安全的队列，自动处理等待和唤醒
 * 推荐用于生产者-消费者模式
 */
public class BlockingQueueExample {

    public static void demo() throws InterruptedException {
        // 创建一个容量为3的阻塞队列
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(3);

        // 生产者线程
        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    String data = "商品-" + i;
                    queue.put(data);  // 如果队列满，自动等待
                    System.out.println("【生产】" + data + ", 队列大小: " + queue.size());
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // 消费者线程
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    String data = queue.take();  // 如果队列空，自动等待
                    System.out.println("【消费】" + data + ", 队列大小: " + queue.size());
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();

        producer.join();
        consumer.join();

        System.out.println("生产和消费完成!");
    }
}

